/**
 * 人脸检测辅助工具
 * 用于主理人申请页面的人脸识别功能
 */

class FaceDetection {
	constructor() {
		this.isDetecting = false
		this.detectionTimer = null
		this.detectionCallback = null
		this.detectionHistory = []
		this.consecutiveDetections = 0
		this.requiredConsecutiveDetections = 3 // 需要连续检测到的次数
	}

	/**
	 * 开始人脸检测
	 * @param {Function} callback 检测结果回调函数
	 * @param {Number} interval 检测间隔（毫秒）
	 */
	startDetection(callback, interval = 1000) {
		if (this.isDetecting) {
			this.stopDetection()
		}

		this.isDetecting = true
		this.detectionCallback = callback
		this.consecutiveDetections = 0

		this.detectionTimer = setInterval(() => {
			this.performDetection()
		}, interval)

		console.log('人脸检测已启动')
	}

	/**
	 * 停止人脸检测
	 */
	stopDetection() {
		if (this.detectionTimer) {
			clearInterval(this.detectionTimer)
			this.detectionTimer = null
		}
		this.isDetecting = false
		this.consecutiveDetections = 0
		console.log('人脸检测已停止')
	}

	/**
	 * 执行人脸检测
	 * 这里使用模拟算法，实际项目中应该调用真实的人脸识别API
	 */
	performDetection() {
		// 模拟人脸检测算法
		// 在实际项目中，这里应该：
		// 1. 获取相机当前帧
		// 2. 调用人脸识别API（如腾讯云、阿里云、百度AI等）
		// 3. 分析人脸位置、角度、清晰度等
		
		const mockDetectionResult = this.mockFaceDetection()
		
		if (mockDetectionResult.detected) {
			this.consecutiveDetections++
			this.detectionHistory.push({
				timestamp: Date.now(),
				confidence: mockDetectionResult.confidence,
				faceRect: mockDetectionResult.faceRect
			})

			// 只有连续检测到指定次数才认为检测成功
			if (this.consecutiveDetections >= this.requiredConsecutiveDetections) {
				this.detectionCallback && this.detectionCallback({
					detected: true,
					confidence: mockDetectionResult.confidence,
					faceRect: mockDetectionResult.faceRect,
					quality: this.calculateQuality()
				})
			}
		} else {
			this.consecutiveDetections = Math.max(0, this.consecutiveDetections - 1)
			
			if (this.consecutiveDetections === 0) {
				this.detectionCallback && this.detectionCallback({
					detected: false,
					reason: mockDetectionResult.reason
				})
			}
		}
	}

	/**
	 * 模拟人脸检测
	 * @returns {Object} 检测结果
	 */
	mockFaceDetection() {
		// 模拟不同的检测情况
		const scenarios = [
			{ detected: true, confidence: 0.95, reason: '' },
			{ detected: true, confidence: 0.88, reason: '' },
			{ detected: false, reason: '未检测到人脸' },
			{ detected: false, reason: '人脸角度过大' },
			{ detected: false, reason: '光线不足' },
			{ detected: true, confidence: 0.92, reason: '' }
		]

		const randomIndex = Math.floor(Math.random() * scenarios.length)
		const result = scenarios[randomIndex]

		// 如果检测到人脸，生成模拟的人脸框坐标
		if (result.detected) {
			result.faceRect = {
				x: 0.3 + Math.random() * 0.4, // 0.3-0.7之间
				y: 0.2 + Math.random() * 0.3, // 0.2-0.5之间
				width: 0.2 + Math.random() * 0.1, // 0.2-0.3之间
				height: 0.25 + Math.random() * 0.1 // 0.25-0.35之间
			}
		}

		return result
	}

	/**
	 * 计算检测质量
	 * @returns {String} 质量等级
	 */
	calculateQuality() {
		if (this.detectionHistory.length === 0) return 'unknown'

		const recentDetections = this.detectionHistory.slice(-this.requiredConsecutiveDetections)
		const avgConfidence = recentDetections.reduce((sum, detection) => sum + detection.confidence, 0) / recentDetections.length

		if (avgConfidence >= 0.9) return 'excellent'
		if (avgConfidence >= 0.8) return 'good'
		if (avgConfidence >= 0.7) return 'fair'
		return 'poor'
	}

	/**
	 * 获取检测历史
	 * @returns {Array} 检测历史记录
	 */
	getDetectionHistory() {
		return this.detectionHistory
	}

	/**
	 * 清空检测历史
	 */
	clearHistory() {
		this.detectionHistory = []
		this.consecutiveDetections = 0
	}

	/**
	 * 检查相机权限
	 * @returns {Promise<Boolean>} 是否有权限
	 */
	static async checkCameraPermission() {
		return new Promise((resolve) => {
			uni.getSetting({
				success: (res) => {
					const hasPermission = res.authSetting['scope.camera'] === true
					resolve(hasPermission)
				},
				fail: () => {
					resolve(false)
				}
			})
		})
	}

	/**
	 * 请求相机权限
	 * @returns {Promise<Boolean>} 是否获得权限
	 */
	static async requestCameraPermission() {
		return new Promise((resolve) => {
			uni.authorize({
				scope: 'scope.camera',
				success: () => {
					resolve(true)
				},
				fail: () => {
					uni.showModal({
						title: '权限申请',
						content: '需要相机权限才能使用人脸识别功能，请在设置中开启',
						confirmText: '去设置',
						success: (modalRes) => {
							if (modalRes.confirm) {
								uni.openSetting({
									success: (settingRes) => {
										resolve(settingRes.authSetting['scope.camera'] === true)
									},
									fail: () => {
										resolve(false)
									}
								})
							} else {
								resolve(false)
							}
						}
					})
				}
			})
		})
	}

	/**
	 * 创建拍照震动反馈
	 */
	static createCaptureVibration() {
		// #ifdef MP-WEIXIN
		uni.vibrateShort({
			type: 'medium'
		})
		// #endif
		
		// #ifdef APP-PLUS
		plus.device.vibrate(100)
		// #endif
	}

	/**
	 * 创建成功提示音效
	 */
	static createSuccessSound() {
		// 在实际项目中可以播放提示音
		console.log('播放成功提示音')
	}
}

export default FaceDetection 